package com.cicigodd.brick.plug.system.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.cicigodd.brick.plug.common.enums.StatusEnum;
import com.cicigodd.brick.plug.system.auth.api.AuthServiceContext;
import com.cicigodd.brick.plug.system.mybatisplus.constants.FieldConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectionException;

import java.util.Date;


/**
 * 字段自动填充工具
 *
 * @author cicigodd
 * @date 2022/09/23 08:42:00
 */
@Slf4j
public class CustomMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {

        try {
            // 设置createUser
            setFieldValByName(FieldConstants.CREATE_USER, this.getUserUniqueId(), metaObject);

            // 设置createTime
            setFieldValByName(FieldConstants.CREATE_TIME, new Date(), metaObject);

            // 设置删除标记 默认N-删除
            setFieldValByName(FieldConstants.DEL_FLAG, "N", metaObject);

        } catch (ReflectionException e) {
            log.warn("无相关字段不做处理");
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {

        try {

            // 设置updateUser
            setFieldValByName(FieldConstants.UPDATE_USER, this.getUserUniqueId(), metaObject);

            // 设置updateTime
            setFieldValByName(FieldConstants.UPDATE_TIME, new Date(), metaObject);

        } catch (ReflectionException e) {
            log.warn("无相关字段不做处理");
        }

    }

    /**
     * 获取用户唯一id
     */
    private Integer getUserUniqueId() {
        try {
            return AuthServiceContext.me().getLoginUser().getUserId();
        } catch (Exception e) {
            //如果获取不到就返回-1
            return -1;
        }

    }

}
